package springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import springcloud.entities.CommonResult;
import springcloud.entities.Payment;
import springcloud.service.PaymentService;

import javax.annotation.Resource;

@RestController
@Slf4j
public class CircleBreakerController {
    @Value("${service-url.nacos-user-service}")
    private String SERVICE_URL;

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/fallback/{id}")
    //@SentinelResource(value = "fallback", fallback = "handlerFallback") //业务异常
    @SentinelResource(value = "fallback", blockHandler = "blockHandler") //控制台配置违规
    //@SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler") //同时配置业务异常和控制台配置违规
    //@SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler", exceptionsToIgnore = {IllegalArgumentException.class}) //忽略降级
    public CommonResult<Payment> fallback(@PathVariable("id") Long id){
        if (id == 4) {
            throw new IllegalArgumentException("非法参数异常");
        }
        //CommonResult<Payment> commonResult = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
        CommonResult<Payment> commonResult = restTemplate.getForObject(SERVICE_URL + "/payment/get/" + id, CommonResult.class, id);
        if (commonResult.getData() == null) {
            throw new NullPointerException("NullPointException，该 ID 没有对应记录，空指针异常");
        }
        return commonResult;
    }
/*    public CommonResult handlerFallback(@PathVariable("id") Long id, Throwable e) {
        return new CommonResult(444,"ParameterException, 非法参数异常" + e.getMessage(), new Payment(id, "null"));
    }*/
    public CommonResult blockHandler(@PathVariable("id") Long id, BlockException e) {
        return new CommonResult(444,"LimitException, 限流异常" + e.getMessage(), new Payment(id, "null"));
    }

    @Resource
    private PaymentService paymentService;
    @GetMapping(value = "/consumer/payment/get/{id}")

    public CommonResult<Payment> getPaymentById(@PathVariable("id")Long id){
        return paymentService.getPaymentById(id);
    }
}
